package com.hancheng.ordercloud.business.service.serviceImpl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hancheng.commoncloud.business.entity.dto.IdDTO;
import com.hancheng.commoncloud.business.entity.dto.IdListDTO;
import com.hancheng.commoncloud.framework.contant.Constants;
import com.hancheng.commoncloud.framework.result.PageResult;
import com.hancheng.commoncloud.framework.result.Response;
import com.hancheng.commoncloud.framework.util.ApiAssert;
import com.hancheng.commoncloud.framework.util.LocalUserInfoUtil;
import com.hancheng.ordercloud.business.entity.dto.OrderDTO;
import com.hancheng.ordercloud.business.entity.dto.OrderInsertDTO;
import com.hancheng.ordercloud.business.entity.dto.SubtractQuantityDTO;
import com.hancheng.ordercloud.business.entity.dto.UserInsertTestDTO;
import com.hancheng.ordercloud.business.entity.po.OrderPO;
import com.hancheng.ordercloud.business.entity.vo.OrderVO;
import com.hancheng.ordercloud.business.mapper.OrderMapper;
import com.hancheng.ordercloud.business.service.OrderService;
import com.hancheng.ordercloud.feign.service.GoodsFeignService;
import com.hancheng.ordercloud.feign.service.UserFeignService;
import com.hancheng.ordercloud.framework.util.GenerateCodeUtil;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.util.List;

/**
 * 订单表 ServiceImpl
 *
 * @author 韩诚
 * @date 2025/06/22
 */
@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private MapperFacade mapperFacade;
    @Autowired
    private GoodsFeignService goodsFeignService;
    @Autowired
    private UserFeignService userFeignService;

    @Autowired
    private DataSource dataSource;

    @PostConstruct
    public void check() {
        System.out.println("当前数据源类型为：" + dataSource.getClass().getName());
    }

    /**
     * 分页列表
     *
     * @param orderDTO
     * @return
     */
    @Override
    public PageResult<OrderVO> getPageList(OrderDTO orderDTO) {
        //获取分页列表
        PageHelper.startPage(orderDTO.getPageNo(), orderDTO.getPageSize());
        List<OrderPO> orderPOList = orderMapper.selectList(new LambdaQueryWrapper<OrderPO>().like(StrUtil.isNotBlank(orderDTO.getOrderCode()), OrderPO::getOrderCode, orderDTO.getOrderCode()).eq(ObjectUtil.isNotNull(orderDTO.getOrderStatus()), OrderPO::getOrderStatus, orderDTO.getOrderStatus()).ge(StrUtil.isNotBlank(orderDTO.getDeliverTimeStart()), OrderPO::getDeliverTime, orderDTO.getDeliverTimeStart()).le(StrUtil.isNotBlank(orderDTO.getDeliverTimeEnd()), OrderPO::getDeliverTime, orderDTO.getDeliverTimeEnd()).orderByDesc(OrderPO::getCreateTime));
        List<OrderVO> orderVOList = mapperFacade.mapAsList(orderPOList, OrderVO.class);

        //新增其他信息
        if (CollUtil.isNotEmpty(orderVOList)) {
            orderVOList.forEach(orderVO -> {

            });
        }

        //整理数据并返回给前端
        PageInfo<OrderVO> pageInfo = new PageInfo<>(orderVOList);
        return new PageResult<>(pageInfo.getTotal(), orderVOList);
    }

    /**
     * 下拉框列表
     *
     * @param orderDTO
     * @return
     */
    public List<OrderVO> getList(OrderDTO orderDTO) {
        List<OrderPO> orderPOList = orderMapper.selectList(new LambdaQueryWrapper<OrderPO>().like(StrUtil.isNotBlank(orderDTO.getOrderCode()), OrderPO::getOrderCode, orderDTO.getOrderCode()).eq(ObjectUtil.isNotNull(orderDTO.getOrderStatus()), OrderPO::getOrderStatus, orderDTO.getOrderStatus()).ge(StrUtil.isNotBlank(orderDTO.getDeliverTimeStart()), OrderPO::getDeliverTime, orderDTO.getDeliverTimeStart()).le(StrUtil.isNotBlank(orderDTO.getDeliverTimeEnd()), OrderPO::getDeliverTime, orderDTO.getDeliverTimeEnd()).orderByDesc(OrderPO::getCreateTime));
        return mapperFacade.mapAsList(orderPOList, OrderVO.class);
    }

    /**
     * 明细
     *
     * @param idDTO
     * @return
     */
    @Override
    public OrderVO detail(IdDTO idDTO) {
        //获取订单信息
        OrderPO orderPO = orderMapper.selectById(idDTO.getId());
        OrderVO orderVO = mapperFacade.map(orderPO, OrderVO.class);

        //添加其他数据
        if (ObjectUtil.isNotNull(orderVO)) {

        }

        //返回数据给前端
        return orderVO;
    }

    /**
     * 新增
     *
     * @param orderInsertDTO
     * @return
     */
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public void insert(OrderInsertDTO orderInsertDTO) {
        System.out.println("当前 Seata 全局事务ID (XID): " + RootContext.getXID());

        //新增订单
        OrderPO orderPO = mapperFacade.map(orderInsertDTO, OrderPO.class);
        orderPO.setOrderCode(GenerateCodeUtil.getOrderCode());
        orderPO.setCreateUserId(LocalUserInfoUtil.getAdminUserPO().getUserId());
        orderMapper.insert(orderPO);

        //新增订单商品

        //新增用户
        Response<Void> userResponse = userFeignService.insertTest(UserInsertTestDTO
                .builder()
                .userName(orderInsertDTO.getRemark())
                .build());
        ApiAssert.isTrue(ObjectUtil.isNotNull(userResponse) && ObjectUtil.equal(userResponse.getResCode(), Constants.ONE), "调用user模块异常！");

        //扣减商品库存数量
        Response<Void> goodsResponse = goodsFeignService.subtractQuantity(SubtractQuantityDTO.builder().goodsId(1).quantity(10).build());
        ApiAssert.isTrue(ObjectUtil.isNotNull(goodsResponse) && ObjectUtil.equal(goodsResponse.getResCode(), Constants.ONE), "调用goods模块异常！");
    }

    /**
     * 批量删除
     *
     * @param idListDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class, timeout = Constants.TIME_OUT)
    @Override
    public void deleteBatch(IdListDTO idListDTO) {
        if (CollUtil.isNotEmpty(idListDTO.getIdList())) {
            //删除订单
            orderMapper.deleteBatchIds(idListDTO.getIdList());

            //删除订单商品

        }
    }
}
